<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CabinetModel
 *
 * @author Admin
 */
class Application_Model_CabinetModel extends Zend_Db_Table_Abstract {

    protected $_name = 'cabinet_mgmt';
    protected $_fields = 'id,name,code,status';
    public $adapter;

    function init() {
        $this->adapter = $this->getAdapter();
    }

    function getAllCabinets($request) {
        $select = $this->select()
                ->from($this->_name, array('id', 'name', 'code', 'status'));
        $dbSelectPaginator = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($dbSelectPaginator);
        $paginator->setCurrentPageNumber($request->getParam('page'));
        $paginator->setPageRange(5);
        $paginator->setItemCountPerPage(5);
        return $paginator;
    }

    function save($data) {
        if (isset($data['id'])) {
            return $this->update($data, "id = $data[id]");
        } else {
            return $this->insert($data);
        }
    }

    function getCabinet($field, $value) {
        return $this->adapter->fetchRow("select $this->_fields from $this->_name where $field = '$value'");
    }

    function getCabinetProgeress($request,$cabinetId = 0) {

        $select = $this->adapter->select()
                ->from($this->_name, array('id', 'name', 'code', 'status'));
        if ($cabinetId) {
            $select->joinLeft('switch_mgmt', "switch_mgmt.cabinet = $this->_name.id", array('id as switch_id','name as switch_name', 'planning_percent_done as progress'))
                    ->WHERE("cabinet_mgmt.id = '$cabinetId'");
        } else {
            $select->joinLeft('switch_mgmt', "switch_mgmt.cabinet = $this->_name.id", array('name as switch_name', 'avg(planning_percent_done) as progress'))
                ->group("switch_mgmt.cabinet");
        }

        $dbSelectPaginator = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($dbSelectPaginator);
        $paginator->setCurrentPageNumber($request->getParam('page'));
        $paginator->setPageRange(5);
        $paginator->setItemCountPerPage(5);
        return $paginator;
    }

}